#!/usr/bin/python
# _*_ coding:utf-8 _*_

import cv2
import math
import sys
import time
from six.moves import input

try:
    from common import screenshot
    from common.auto_adb import auto_adb
except Exception as ex:
    print(ex)
    print('请将脚本放在项目根目录中运行')
    print('请检查项目根目录中的 common 文件夹是否存在')
    exit(1)

adb = auto_adb()

scale = 1

# RGB 值误差范围
error_range = [20, 20, 20]

minRadius = int(100 * scale)
maxRadius = int(300 * scale)
touch_area = cv2.imread('./temp/touch_area.png')
touch_area = cv2.resize(touch_area, (0, 0), fx=scale, fy=scale)
rows, cols, channels = touch_area.shape

# 列表可点击区域范围
hand_area_min_width = 900 * scale
hand_area_max_width = 1080 * scale

# 列表“换一批”点击的位置
next_page_x = 545 * scale
next_page_y = 1700 * scale

# 处理列表页
hand_tmp = cv2.imread('./resource/image/hand.png')
hand_tmp = cv2.resize(hand_tmp, (0, 0), fx=scale, fy=scale)
hand_tmp_width = hand_tmp.shape[0]
hand_tmp_height = hand_tmp.shape[1]


# 搜索 img 图片中 template 的位置，返回图片的左上角坐标
def search_touch_point(img, template):
    result = cv2.matchTemplate(img, template, cv2.TM_SQDIFF)
    min_val, max_val, min_loc, max_loc = cv2.minMaxLoc(result)
    print('search_touch_point:x = {} y = {}'.format(min_loc[0], min_loc[1]))
    return min_loc[0], min_loc[1]


def search(file_path, template):
    img = cv2.imread(file_path)
    return search_touch_point(img, template)


def hand_search(img):
    touch_x, touch_y = search_touch_point(img, hand_tmp)
    if touch_x > hand_area_max_width:
        return 0, 0
    if touch_x < hand_area_min_width:
        return 0, 0
    return touch_x, touch_y + hand_tmp_height


def rgb2hsv(b, g, r):
    r, g, b = r/255.0, g/255.0, b/255.0
    mx = max(r, g, b)
    mn = min(r, g, b)
    df = mx-mn
    if mx == mn:
        h = 0
    elif mx == r and g >= b:
        h = 60 * ((g - b) / df) + 0
    elif mx == r and g < b:
        h = 60 * ((g-b)/df) + 360
    elif mx == g:
        h = 60 * ((b-r)/df) + 120
    elif mx == b:
        h = 60 * ((r-g)/df) + 240
    if mx == 0:
        s = 0
    else:
        s = df/mx
    v = mx
    return h, s, v


def click_able(image):
    pc = 3
    len = 10
    _rows, _cols, _channels = image.shape
    start_rows = 40
    if _rows < 40:
        start_rows = _rows
    start_cols = 40
    if _cols < 40:
        start_cols = _cols
    count = 0
    for y in range(0, start_cols):
        for x in range(0, start_rows):
            c = image[x, y]
            if c[0] == 255 and c[1] == 255 and c[2] == 255:
                break
            if abs(c[0] - 224) < pc and c[1] > 200:
                if count > len:
                    return True, (c[0], c[1], c[2])
                count = count + 1
    return False, None


def getContourRGBTotalValue(imgsrc, x, y, w, h):
    total = 0
    for i in range(0, 5):
        xx = x + int(i / 5 * w)
        for j in range(0, 5):
            yy = y + int(j / 5 * h)
            if xx < rows and yy < cols:
                temp = imgsrc[xx, yy]
                h, s, v = rgb2hsv(temp[0], temp[1], temp[2])
                # print(h, s, v)
                if h > 50:
                    total = int(total + h)
                # 方法 1
                # total = total + imgsrc[xx, yy][0] + imgsrc[xx, yy][1] + imgsrc[xx, yy][2]
                # 方法 2
                # if imgsrc[xx, yy][0] > 200 and imgsrc[xx, yy][1] > 200:
                #     return 3001
    return total


def get_touch_range(img):
    for i in range(rows):
        for j in range(cols):
            if (touch_area[i, j] == [0, 0, 0]).all():
                img[i, j] = [0, 0, 0]
            else:
                temp = img[i, j] - touch_area[i, j]
                temp[0] = math.fabs(temp[0])
                temp[1] = math.fabs(temp[1])
                temp[2] = math.fabs(temp[2])
                if (temp < error_range).all():
                    img[i, j] = [0, 0, 0]
                else:
                    img[i, j] = [255, 255, 255]
    # 腐蚀 3 次
    erode = cv2.erode(img, None, iterations=3)
    # 膨胀
    dilate = cv2.dilate(erode, None, iterations=3)
    # 获取轮廓
    img_gray = cv2.cvtColor(dilate, cv2.COLOR_BGR2GRAY)
    image, contours, hierarchy = cv2.findContours(img_gray, cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPLE)

    img_hsv = cv2.cvtColor(img, cv2.COLOR_BGR2HSV)
    touchs = []
    for i in range(0, len(contours)):
        cnt = contours[i]
        x, y, w, h = cv2.boundingRect(cnt)
        # 计算该轮廓的面积，面积小的都筛选掉
        if cv2.contourArea(cnt) < 500:
            continue

        center = (x + int(w / 2), y + int(h / 2))
        crop_img = img[y:(y + h), x:(x + w)]
        clickable, cxxx = click_able(crop_img)
        touchs.append({'x': x, 'y': y, 'w': w, 'h': h, 'center': center, 'clickable': clickable})

    return touchs


# 模拟点击屏幕
def phone_touch(touch_x, touch_y):
    cmd = 'shell input tap {0} {1} '.format(touch_x, touch_y)
    print(cmd)
    adb.run(cmd)


# 模拟点击返回
def phone_back():
    cmd = 'shell input keyevent 4'
    print(cmd)
    adb.run(cmd)

def main():
    # 读取文件
    while 1:
        img = screenshot.pull_screenshot()
        img = cv2.resize(img, (0, 0), fx=scale, fy=scale)
        touch_x, touch_y = hand_search(img)
        print('定位：x = {} y = {}'.format(touch_x, touch_y))
        if touch_x > 0 and touch_y > 0:
            phone_touch(touch_x, touch_y)
            print('hand 程序将在 1秒 后继续，', time.strftime("%Y-%m-%d %H:%M:%S", time.localtime()))
            time.sleep(0.1)
            while 1:
                img = screenshot.pull_screenshot()
                img = cv2.resize(img, (0, 0), fx=scale, fy=scale)
                touchs = get_touch_range(img)
                has_t = False
                print('touchs 个数', len(touchs), time.strftime("%Y-%m-%d %H:%M:%S", time.localtime()))
                for t in touchs:
                    if t['clickable']:
                        has_t = True
                        print('定位：x = {} y = {} , total = {}'.format(t['x'], t['y'], t['clickable']))
                        phone_touch(t['center'][0], t['center'][1])
                        print('star 程序继续运行中', time.strftime("%Y-%m-%d %H:%M:%S", time.localtime()))

                if has_t == False:
                    for t in touchs:
                        has_t = True
                        print('定位：x = {} y = {}'.format(t['x'], t['y']))
                        phone_touch(t['center'][0], t['center'][1])
                        print('star 程序继续运行中', time.strftime("%Y-%m-%d %H:%M:%S", time.localtime()))
                time.sleep(0.1)
                phone_back()
                break
        else:
            print('hand 程序将在 2秒 后继续', time.strftime("%Y-%m-%d %H:%M:%S", time.localtime()))
            time.sleep(2)
            # 刷新列表
            phone_touch(next_page_x, next_page_y)


if __name__ == '__main__':
    try:
        adb.test_device()
        main()

        # img = cv2.imread('./temp/124105.png')
        # img = cv2.resize(img, (0, 0), fx=scale, fy=scale)
        # touchs = get_touch_range(img)
        # if touchs != None:
        #     index = 0
        #     for t in touchs:
        #         print(t['x'], t['y'], t['w'], t['h'])
        #         cropImg = img[t['y']:(t['y'] + t['h']), t['x']:(t['x'] + t['w'])]
        #         cv2.imwrite(str(index) + ".png", cropImg)
        #         index = index + 1
        #
        #         cv2.rectangle(img, (t['x'], t['y']), (t['x'] + t['w'], t['y'] + t['h']), (0, 255, 0), 2)
        #     cv2.imshow('img', img)
        #     cv2.imwrite("img.png", img)
        #     cv2.waitKey(0)
        # else:
        #     print('None')
    except KeyboardInterrupt:
        adb.run('kill-server')
        print('\n谢谢使用', end='')
        exit(0)

